#!/usr/bin/env python3
#
# vim: set expandtab shiftwidth=4 tabstop=4:
#
# This file is part of libratbag.
#
# Copyright 2017 Red Hat, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice (including the next
# paragraph) shall be included in all copies or substantial portions of the
# Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.

import os
import time
import toolbox
import signal
import sys
from ratbagctl import RatbagErrorCapability  # NOQA


def main(argv):
    if not os.geteuid() == 0:
        sys.exit('Script must be run as root')

    os.environ['LIBRATBAG_DATA_DIR'] = '@LIBRATBAG_DATA_DIR@'

    if not argv:
        argv = ["list"]

    cmd = None
    ratbagd_process = None
    try:
        parser = toolbox.get_parser()
        parser.want_keepalive = True
        cmd = parser.parse(argv)
        if cmd.help:
            parser.print_help()
            return

        ratbagd_process = toolbox.start_ratbagd(verbosity=cmd.verbose)
        if ratbagd_process is None:
            sys.exit("Failed to start or connect to ratbagd")

        _ratbagd = toolbox.open_ratbagd()
        if _ratbagd is not None:
            with _ratbagd as ratbagd:
                try:
                    f = cmd.func
                except AttributeError:
                    parser.print_help()
                    return
                else:
                    try:
                        f(ratbagd, cmd)
                        # give time for ratbagd to receive async requests before
                        # we try to terminate it
                        time.sleep(0.5)
                    except RatbagErrorCapability as e:
                        print("Error: {}".format(e), file=sys.stderr)
    finally:
        try:
            if cmd.keepalive:
                print('\nexport RATBAGCTL_DEVEL="{}"\n'.format(os.environ['RATBAGCTL_DEVEL']))
                signal.pause()
        except KeyboardInterrupt:
            pass
        except AttributeError:  # in case the parsing failed and cmd is None
            pass
        toolbox.terminate_ratbagd(ratbagd_process)


if __name__ == "__main__":
    main(sys.argv[1:])
